package cn.rui.decoration.controller;
import cn.rui.decoration.mapper.UserMapper;
import cn.rui.decoration.pojo.dto.UserDTO;
import cn.rui.decoration.pojo.entity.User;
import cn.rui.decoration.pojo.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired(required = false)
    UserMapper mapper;
    @RequestMapping("/user/login")
    public int login(@RequestBody UserDTO user, HttpServletResponse response,HttpSession session){

        System.out.println("user = " + user);
        UserVO u = mapper.selectByUsername(user.getUsername());
        if (u!=null){
            if (u.getPassword().equals(user.getPassword())){
                session.setAttribute("user",u);
                if (user.getRem()){
                    Cookie c1 = new Cookie("username",user.getUsername());
                    Cookie c2 = new Cookie("password",user.getPassword());
                    c1.setMaxAge(60*60*24);
                    c2.setMaxAge(60*60*24);
                    response.addCookie(c1);
                    response.addCookie(c2);
                }
                return 1;
            }
            return 3;
        }
        return 2;
    }
    @RequestMapping("/user/reg")
    public int reg(@RequestBody User user){
        UserVO u = mapper.selectByUsername(user.getUsername());
        if(u!=null){
            return 2;
        } else if(user.getUsername().equals("")||user.getUsername()==null||
        user.getPassword().equals("")||user.getPassword()==null||
        user.getAddress().equals("")||user.getAddress()==null||
        user.getTel().equals("")||user.getTel()==null){
            return 3;
        }
        mapper.insert(user);
        return 1;
    }

    @RequestMapping("/user/update")
    public int update(@RequestBody UserDTO user){
        UserVO u = mapper.selectByUsername(user.getUsername());
        if(u!=null){
            mapper.updateByUsername(user);
            return 1;
        }
        return 2;
    }

    @RequestMapping("/currentUser")
    public UserVO currentUser(HttpSession session){
        return (UserVO) session.getAttribute("user");
    }
}
